const fs = require('fs');
const path = require('path');
const Kuroshiro = require('kuroshiro').default;
const KuromojiAnalyzer = require('kuroshiro-analyzer-kuromoji');

// 指定目录
const targetDirectory = './';

// 初始化 Kuroshiro
const kuroshiro = new Kuroshiro();
async function initKuroshiro() {
    const analyzer = new KuromojiAnalyzer();
    await kuroshiro.init(analyzer);
}

// 遍历指定目录下的所有 .lrc 文件
function traverseLrcFiles() {
    fs.readdir(targetDirectory, (err, files) => {
        if (err) {
            console.error('读取目录时出错:', err);
            return;
        }
        files.forEach(file => {
            if (path.extname(file) === '.lrc') {
                const filePath = path.join(targetDirectory, file);
                convertLrcFile(filePath);
            }
        });
    });
}

// 转换单个 LRC 文件
async function convertLrcFile(filePath) {
    try {
        const data = fs.readFileSync(filePath, 'utf8');
        const lines = data.split('\n');
        const convertedLines = [];
        for (const line of lines) {
            const convertedLine = await kuroshiro.convert(line, { to: 'hiragana' });
            convertedLines.push(convertedLine);
        }
        const convertedContent = convertedLines.join('\n');
        const outputFilePath = path.join(targetDirectory, path.basename(filePath, '.lrc') + '_converted.lrc');
        fs.writeFileSync(outputFilePath, convertedContent, 'utf8');
        console.log(`转换完成: ${filePath} -> ${outputFilePath}`);
    } catch (error) {
        console.error(`处理文件 ${filePath} 时出错:`, error);
    }
}

// 主函数
async function main() {
    await initKuroshiro();
    traverseLrcFiles();
}

main();